package com.sky.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: UserServiceImpl
 * USER: zhang
 * DATE: 2023/5/21
 * DESCRIPTION :C端-用户信息表现层实现类
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private JwtProperties jwtProperties;
    //抽取微信登录的校验接口
    private static final String WI_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户登录功能
     *
     * @param userLoginDTO 用户登录dto
     * @return 全局通用返回信息Bean(本次登录用户的Id / 微信的OpenId / 生成的Jwt令牌)
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //向微信请求获取openId,
        //封装请求参数Map并调用提供的HttpClientUtils工具类提供发送GET请求的方法获取结果
        HashMap<String,String> paramaterMap = new HashMap<>();
        paramaterMap.put("appid",weChatProperties.getAppid());
        paramaterMap.put("secret",weChatProperties.getSecret());
        paramaterMap.put("js_code",userLoginDTO.getCode());
        paramaterMap.put("grant_type","authorization_code");

        String loginResult = HttpClientUtil.doGet(WI_LOGIN_URL, paramaterMap);
        //如果是一个Json格式的字符串先将它转换为一个JSONObject的对象
        JSONObject wxLoginObject = JSON.parseObject(loginResult);
        //基于getString(传递键的名称获取值)
        String openid = wxLoginObject.getString("openid");
        //判断当前用户中是否存在该openid对应的用户信息
        User user = userMapper.selectUserByOpenid(openid);
        if (Objects.isNull(user)){
            //如果没有查询到openid对应的用户信息，，封装一个user添加到表中
            user  = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);//返回主键
        }
        //生成令牌基于JWTUtil
        HashMap<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwtToken = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        return UserLoginVO.builder().id(user.getId()).openid(openid).token(jwtToken).build();
    }
}
